package com.yeshen.pmtea.fragments;


import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.yeshen.pmtea.R;
import com.yeshen.pmtea.adapters.MyPagerAdapter;
import com.yeshen.pmtea.adapters.NewsAdapter;
import com.yeshen.pmtea.beans.News;
import com.yeshen.pmtea.beans.Urls;
import com.yeshen.pmtea.callback.NewsCallback;
import com.yeshen.pmtea.net.NewsAsyncTask;
import com.yeshen.pmtea.ui.NewsItemContentActivity;
import com.yeshen.pmtea.utils.NetworkUtils;
import com.yeshen.pmtea.utils.ParseJsonToList;
import com.yeshen.pmtea.utils.SdCardUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class FristFragment extends Fragment implements ViewPager.OnPageChangeListener, AdapterView.OnItemLongClickListener, AbsListView.OnScrollListener {
    private ListView mListView;
    private TextView empty;
    private PullToRefreshListView mPullToRefreshListView;
    private ViewPager mViewPager;
    private LinearLayout llPoints;
    private List<ImageView> imgList,pointList;
    private int[] imgs=new int[]{R.mipmap.viewpager01,R.mipmap.viewpager02,R.mipmap.viewpager03};
    private Handler mHandler =new Handler();

    private BaseAdapter adapter;
    private List<News> newsList =new ArrayList<>();;

    private int page =1;
    private boolean isDown=false;

    public FristFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_frist, container, false);
        initView(view);
        View headView =
                LayoutInflater
                        .from(getContext()).inflate(R.layout.head_item,mListView,false);
        mViewPager= (ViewPager) headView.findViewById(R.id.viewPager01);
        llPoints= (LinearLayout) headView.findViewById(R.id.ll_points);
        //3图3点-数据
        initData();
        //对viewPager设置适配器
        mViewPager.setAdapter(new MyPagerAdapter(imgList,getContext()));
        mViewPager.addOnPageChangeListener(this);
        //利用handler进行无限轮播
        automaticViewPager();
        //头已好 可添加
        mListView.addHeaderView(headView);
        loadData();
        initListView();
        return view;
    }

    private void loadData() {
        String root = getContext().getExternalCacheDir().getAbsolutePath();
        String fileName = root+ File.separator+"news";
        byte[] bytes = SdCardUtils.getbyteFromFile(fileName);
        if (bytes != null) {
            News news = (News) ParseJsonToList.parseJsonToNewsList(new String(bytes));
            newsList.add(news);
            adapter.notifyDataSetChanged();
        }else {
            if (NetworkUtils.isConnected(getContext())){
                new NewsAsyncTask(new NewsCallback() {
                    @Override
                    public void callbackNews(List result) {
                        //保存数据到sd卡
                        //字符串数据toString ,字节数据 getBytes
                        byte[] bytes1 =result.toString().getBytes();
                        String root = getContext().getExternalCacheDir().getAbsolutePath();
                        String fileName = "news";
                        Log.d("flag", "----------------->handleMessage: " +fileName);
                        SdCardUtils.saveFile(bytes1,root,fileName);
                        // newsList.remove(newsList);
                        newsList.addAll(result);
                        adapter.notifyDataSetChanged();
                        Log.d("flag", "-----------callbackNews: "+result.size());
                    }
                }).execute(Urls.HEADLINE_URL+Urls.HEADLINE_TYPE+page);
            }
        }

    }

    private void automaticViewPager() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){SystemClock.sleep(800);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            int currentItem =mViewPager.getCurrentItem();
                            int newItem =0;
                            if (currentItem==imgList.size()-1){
                                newItem =0;
                            }else {
                                newItem=currentItem+1;
                            }
                            mViewPager.setCurrentItem(newItem);
                        }
                    });
                }
            }
        }).start();
    }

    private void initData() {
        imgList=new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            ImageView imageView=new ImageView(getContext());
            imageView.setImageResource(imgs[i]);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imgList.add(imageView);
        }
        initPointData();

    }

    private void initPointData() {
        pointList =new ArrayList<>();
        int len=imgList.size();
        for (int i = 0; i < len; i++) {
            ImageView imageView=new ImageView(getContext());
            imageView.setBackgroundResource(R.drawable.point_content);
            pointList.add(imageView);
            llPoints.addView(imageView);
        }
        llPoints.getChildAt(0).setEnabled(false);
    }

    private void initListView() {
        adapter =new NewsAdapter(newsList,getContext());
        mListView.setAdapter(adapter);
        mListView.setEmptyView(empty);

        //listViewde 监听进入另一个界面web
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(),NewsItemContentActivity.class);
                News news = newsList.get(position);
                intent.putExtra("key",news);

                startActivity(intent);
            }
        });
        //listView条目监听弹出菜单,删除
        mListView.setOnItemLongClickListener(this);
        //listView分页加载
        mListView.setOnScrollListener(this);
    }
    private void initView(View view) {
        mListView= (ListView) view.findViewById(R.id.listView01);
         empty= (TextView) view.findViewById(R.id.empty);
        //mListView=mPullToRefreshListView.getRefreshableView();
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        for (int i = 0; i < 3; i++) {
            pointList.get(i).setEnabled(true);
        }
        pointList.get(position).setEnabled(false);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
//listView的长按事件
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
        AlertDialog.Builder builder =new AlertDialog.Builder(getContext());
        View view1 = LayoutInflater.from(getContext()).inflate(R.layout.dialog_item, null);
        builder.setView(view1);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //索引越界异常
                newsList.remove(position-1);
                adapter.notifyDataSetChanged();
            }
        });
        builder.setNegativeButton("取消",null);
        builder.create().show();
        return false;
    }
    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        //停止
        if (isDown&&scrollState==SCROLL_STATE_IDLE){
            page++;
            loadData();
        }
    }
    //正在滑动
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        if(totalItemCount!=0){
            if(firstVisibleItem+visibleItemCount==(totalItemCount)){
                isDown =true;
            }else {
                isDown =false;
            }
        }
    }
}
